/*
 * by wlh 
 * date #CreateTime#
 */

using MermaidParser;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using System.Linq;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class InspectObj_Left
{
    DialogueGraphView graphView;

    public InspectObj_Left(DialogueGraphView graphView)
    {
        this.graphView = graphView;
    }

    [TextArea(30, 80)]
    public string mermaidCode=
        @"graph LR
        A[Start]
        B{Process}
        C[End]

        A-->B
        B-->C";

    [Button(ButtonSizes.Small), HorizontalGroup("row1")]
    private void TextToGraph()
    {
        Debug.Log("TextToGraph");

        Debug.Log(mermaidCode);
        Flowchart fc = MermaidExample.Example(mermaidCode);

        graphView.DeleteElements(graphView.nodes);
        graphView.DeleteElements(graphView.edges);
        foreach (var node in fc.Nodes)
        {
            //graphView.AddNode(node.Id, node.Text);
            graphView.AddMermaidNode(node.Id, node.Shape, $"{node.Text}");
        }
        foreach (var link in fc.Links)
        {
            var from = graphView.nodes.First(n => (n.userData as MermaidNode).mermaidId == link.FromNodeId);
            var to = graphView.nodes.First(n => (n.userData as MermaidNode).mermaidId == link.ToNodeId);
            graphView.ConnectEdgeByNode(from, to);
        }

        if (mermaidCode.Contains("PosDef:begin"))
            graphView.LoadPositionsFromMermaid(mermaidCode);
        else
            graphView.OrganizeLayout();
    }

    [Button(ButtonSizes.Small), HorizontalGroup("row1")]
    private void GraphToText()
    {
        Debug.Log("GraphToText");

        mermaidCode = graphView.ExportToMermaid();
    }
}


public class MermaidNode
{
    public NodeShape shape;
    public string mermaidId;
    public string Text;
    public bool Entry = false;
    [ReadOnly]
    public string GUID;

    [Button, HorizontalGroup("row1")]
    void Confirm()
    {
        Debug.Log("confirm");
        MermaidNodeFactory.SetNode(GUID, mermaidId, Text, shape, Entry);
    }

    //[Button, HorizontalGroup("row1")]
    //void Cancel()
    //{
    //    Debug.Log("cancel");

    //}

    public MermaidNode Clone()
    {
        var n = new MermaidNode()
        {
            shape = shape,
            mermaidId = mermaidId,
            Text = Text,
            Entry = Entry,
            GUID = GUID
        };
        return n;
    }
}